package com.iraeta.common;

import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.iraeta.entity.main.User;
import com.iraeta.service.sys.UserService;
import com.iraeta.uitl.JwtUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Component
public class SecurityInterceptor implements HandlerInterceptor {
    @Resource
    UserService userService;

    @Override
    public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3) {

    }

    @Override
    public void postHandle(HttpServletRequest request,
                           HttpServletResponse response, Object obj, ModelAndView model) {

    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handleObj){
        if(handleObj instanceof HandlerMethod){ //有authAccess 不检查权限
            HandlerMethod hm = (HandlerMethod) handleObj;
            //Method method = hm.getMethod(); //listStudent
            //Class<?> clazz = method.getDeclaringClass();    //StudentController
            //System.out.println(clazz.getSimpleName() + "_" + method.getName());

            AuthAccess authAccess = hm.getMethod().getAnnotation(AuthAccess.class);
            if(authAccess != null){
                return true;
            }

            //token检查
            String token = request.getHeader("X-Token");
            if(StrUtil.isBlank(token)){
                throw new ServiceException("401","请登录");
            }

            //jwt验证
            String userIdStr;
            try {
                userIdStr = JWT.decode(token).getAudience().get(0);
            }catch (JWTDecodeException e){
                throw new ServiceException("401","请登录");
            }
            JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(JwtUtil.singKey.concat(userIdStr))).build();
            try {
                jwtVerifier.verify(token);
            }catch (JWTVerificationException e){
                throw new ServiceException("401","请登录");
            }

            //用户信息缓存数据
            int userId = 0;
            MySession session = MySessionManager.get(token);
            if (session.getAttribute("currentUserId") != null) {
                userId = (Integer) session.getAttribute("currentUserId");
            }
            //缓存没有的话
            if(userId == 0){
                User user = userService.getUser(Integer.parseInt(userIdStr));
                if (user==null){
                    throw new ServiceException("401","请登录");
                }
                this.cacheUserInfoInSession(user, session);
            }
        }
        return true;
    }
    public void cacheUserInfoInSession(User user, MySession session){
        session.setAttribute("currentUserId", user.getId());
        session.setAttribute("currentUserName", user.getName());
        session.setAttribute("currentUserAvatar", user.getPhoto());
        List<Integer> permissions = userService.listUserPermissions(user.getId());
        session.setAttribute("permissions", permissions);
    }
}
